/**
 * 请勿修改此处代码，因为插件更新后此处代码会被覆盖。
 * 作者：VK
 * 发布于：2021-07-06
 */
var common = {};

/**
 * 给第三方服务器返回成功通知
 * 每新增一种支付方式，需要在此处添加对应的返回格式
 */
common.returnNotifySUCCESS = function(pay_type) {
	if (pay_type.indexOf("wxpay_") === 0) {
		// 微信支付需返回 xml 格式的字符串
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			headers: {
				'content-type': 'text/xml;charset=utf-8'
			},
			body: "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>"
		};
	} else if (pay_type.indexOf("alipay_") === 0) {
		// 支付宝支付直接返回 success 字符串
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			headers: {
				'content-type': 'text/plain'
			},
			body: "success"
		}
	} else if (pay_type.indexOf("vkspay_") === 0) {
		// VksPay支付返回对象形式 { code: "SUCCESS", msg: "SUCCESS" }
		return {
			code: "SUCCESS",
			msg: "SUCCESS"
		}
	} else if (pay_type.indexOf("wxpay-virtual_") === 0) {
		// 微信虚拟支付返回对象形式 { ErrCode: 0, ErrMsg: "success" }
		return {
			ErrCode: 0,
			ErrMsg: "success"
		}
	} else if (pay_type.indexOf("douyin_") === 0) {
		// 抖音支付返回对象形式 { err_no: 0, err_tips: "success" }
		return {
			err_no: 0,
			err_tips: "success"
		}
	}
	return "success";
};

/**
 * 获取timeExpire
 * let statPlatform = libs.common.getTimeExpire({ time_expire, provider, version });
 */
common.getTimeExpire = function(obj = {}) {
	let {
		time_expire,
		provider,
		version,
		targetTimezone = 8
	} = obj;
	let timeExpire;
	if (provider === "wxpay") {
		// 注意：微信支付的超时时间扫码付最短是1分钟，其他最短是5分钟
		if (version === 3) {
			// 微信支付v3
			timeExpire = common.timeFormat(time_expire, "yyyy-MM-ddThh:mm:ssZ", targetTimezone);
		} else {
			// 微信支付v2
			timeExpire = common.timeFormat(time_expire, "yyyyMMddhhmmss", targetTimezone);
		}
	} else if (provider === "alipay") {
		// 支付宝支付
		timeExpire = common.timeFormat(time_expire, "yyyy-MM-dd hh:mm:ss", targetTimezone);
	} else if (provider === "vkspay") {
		// VksPay个人支付不支持timeExpire参数

	} else if (provider === "douyin") {
		// 抖音支付不支持timeExpire参数

	}
	return timeExpire;
};

/**
 * 新版已经从回调路径中获取到了out_trade_no，此函数仅为了兼容旧版
 * 从event中获取异步通知的参数，并转成json对象
 */
common.getNotifyData = function(event, pay_type) {
	let json = {};
	let body = event.body;
	if (event.isBase64Encoded) {
		body = Buffer.from(body, 'base64').toString('utf-8');
	}
	if (pay_type.indexOf("wxpay_") == 0) {
		// 微信支付官方
		if (body.indexOf("<xml>") > -1) {
			// 微信支付v2
			json = common.parseXML(body);
		} else {
			// 微信支付v3
			json = typeof body === "string" ? JSON.parse(body) : body;
		}
	} else if (pay_type.indexOf("alipay_") == 0) {
		// 支付宝支付官方
		json = common.urlStringToJson(body);
	} else if (pay_type.indexOf("wxpay-virtual_") == 0) {
		// 微信小程序虚拟支付
		json = typeof body === "string" ? JSON.parse(body) : body;
		json.out_trade_no = json.OutTradeNo;
	} else {
		json = common.urlStringToJson(body);
	}
	return json;
};

/**
 * 产生指定位数的随机数(支持任意字符,默认纯数字)
 * @params	{Number} length 数据源
 * @params	{String} str 指定的字符串中随机范围
 */
common.random = function(length, str) {
	let s = "";
	let list = "0123456789";
	//abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
	if (str) list = str;
	for (let i = 0; i < length; i++) {
		let code = list[Math.floor(Math.random() * list.length)];
		s += code;
	}
	return s;
};

/**
 * 日期格式化
 * @params {Date || Number} date 需要格式化的时间
 */
common.timeFormat = function(time, fmt = 'yyyy-MM-dd hh:mm:ss', targetTimezone = 8) {
	try {
		if (!time) {
			return "";
		}
		// 其他更多是格式化有如下:
		// yyyy-MM-dd hh:mm:ss|yyyy年MM月dd日 hh时MM分等,可自定义组合
		let date;
		if (typeof time === "number") {
			if (time.toString().length == 10) time *= 1000;
			date = new Date(time);
		} else {
			date = time;
		}

		const dif = date.getTimezoneOffset();
		const timeDif = dif * 60 * 1000 + (targetTimezone * 60 * 60 * 1000);
		const east8time = date.getTime() + timeDif;

		date = new Date(east8time);
		let opt = {
			"M+": date.getMonth() + 1, //月份
			"d+": date.getDate(), //日
			"h+": date.getHours(), //小时
			"m+": date.getMinutes(), //分
			"s+": date.getSeconds(), //秒
			"q+": Math.floor((date.getMonth() + 3) / 3), //季度
			"S": date.getMilliseconds(), //毫秒
			"Z": `${targetTimezone >= 0 ? '+' : '-'}${Math.abs(targetTimezone).toString().padStart(2, '0')}:00` // Timezone offset
		};
		if (/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
		}
		for (let k in opt) {
			if (new RegExp("(" + k + ")").test(fmt)) {
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (opt[k]) : (("00" + opt[k]).substr(("" + opt[k]).length)));
			}
		}
		return fmt;
	} catch (err) {
		// 若格式错误,则原值显示
		return time;
	}
};


/**
 * request 请求库
 */
common.request = async function(obj = {}) {
	if (Object.prototype.toString.call(obj.content) === "[object object]") obj.content = JSON.stringify(obj.content);
	if (typeof obj.dataType === "undefined") obj.dataType = "json";
	// 当返回的是二进制时,需要设置dataType = default
	if (obj.dataType == "default" || obj.dataType === "") delete obj.dataType;
	if (obj.useContent) obj.content = JSON.stringify(obj.data);
	if (!obj.method) obj.method = "POST";
	if (typeof obj.headers === "undefined" && typeof obj.header !== "undefined") {
		obj.headers = obj.header;
	}
	let originalRes = await uniCloud.httpclient.request(obj.url, obj);
	if (!obj.needOriginalRes && originalRes && originalRes.data) {
		return originalRes.data;
	} else {
		return originalRes;
	}
};
// 是否是手机访问
common.isMobile = function(ua, isPC) {
	if (typeof isPC !== "undefined") return !isPC;
	let system = {
		ios: false,
		android: false
	};
	let p = ua.toLowerCase();
	system.ios = p.indexOf("iphone") > -1 || p.indexOf("ipad") > -1;
	system.android = p.indexOf("android") > -1;
	if (system.ios || system.android) {
		return true;
	} else {
		return false;
	}
};


const isSnakeCase = new RegExp('_(\\w)', 'g');
const isCamelCase = new RegExp('[A-Z]', 'g');

function parseObjectKeys(obj, type) {
	let parserReg;
	let parser;
	switch (type) {
		case 'snake2camel':
			parser = common.snake2camel
			parserReg = isSnakeCase
			break
		case 'camel2snake':
			parser = common.camel2snake
			parserReg = isCamelCase
			break
	}
	for (const key in obj) {
		if (Object.prototype.hasOwnProperty.call(obj, key)) {
			if (parserReg.test(key)) {
				const keyCopy = parser(key)
				obj[keyCopy] = obj[key]
				delete obj[key]
				if (Object.prototype.toString.call((obj[keyCopy])) === '[object Object]') {
					obj[keyCopy] = parseObjectKeys(obj[keyCopy], type)
				} else if (Array.isArray(obj[keyCopy])) {
					obj[keyCopy] = obj[keyCopy].map((item) => {
						return parseObjectKeys(item, type)
					})
				}
			}
		}
	}
	return obj
}

common.snake2camel = function(value) {
	return value.replace(isSnakeCase, (_, c) => (c ? c.toUpperCase() : ''))
}

common.camel2snake = function(value) {
	return value.replace(isCamelCase, str => '_' + str.toLowerCase())
}

// 转驼峰
common.snake2camelJson = function(obj) {
	return parseObjectKeys(obj, 'snake2camel');
};

// 转蛇形
common.camel2snakeJson = function(obj) {
	return parseObjectKeys(obj, 'camel2snake');
};

// url参数转json
common.urlStringToJson = function(str) {
	let json = {};
	if (str != "" && str != undefined && str != null) {
		let arr = str.split("&");
		for (let i = 0; i < arr.length; i++) {
			let arrstr = arr[i].split("=");
			let k = arrstr[0];
			let v = arrstr[1];
			json[k] = v;
		}
	}
	return json;
};

// 简易版XML转Object，只可在微信支付时使用，不支持嵌套
common.parseXML = function(xml) {
	const xmlReg = /<(?:xml|root).*?>([\s|\S]*)<\/(?:xml|root)>/
	const str = xmlReg.exec(xml)[1]
	const obj = {}
	const nodeReg = /<(.*?)>(?:<!\[CDATA\[){0,1}(.*?)(?:\]\]>){0,1}<\/.*?>/g
	let matches = null
	// eslint-disable-next-line no-cond-assign
	while ((matches = nodeReg.exec(str))) {
		obj[matches[1]] = matches[2]
	}
	return obj
};


/**
 * 休眠，等待（单位毫秒）
 * @param {Number} ms 毫秒
 * await common.sleep(1000);
 */
common.sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

/**
 * 获取PLATFORM
 * PLATFORM = libs.common.getPlatform(PLATFORM);
 */
common.getPlatform = function(PLATFORM) {
	if (PLATFORM === "web") {
		// hbx版本>=3.4.12，h5的PLATFORM为web，为了兼容，这里强制设定为h5
		PLATFORM = "h5";
	} else if (PLATFORM === "app") {
		// hbx版本>=3.4.12，app的PLATFORM从app-plus改成了app，为了向下兼容，这里强制设定为app-plus
		PLATFORM = "app-plus";
	}
	return PLATFORM;
};

/**
 * 获取uniPlatform（与getPlatform区别是 h5 = web app-plus = app
 * let uniPlatform = libs.common.getUniPlatform(PLATFORM);
 */
common.getUniPlatform = function(PLATFORM) {
	let uniPlatform = PLATFORM;
	if (uniPlatform === "h5") {
		uniPlatform = "web";
	} else if (uniPlatform === "app-plus") {
		uniPlatform = "app";
	}
	return uniPlatform;
};


/**
 * 获取statPlatform（与getUniPlatform区别是 app平台区分 android 和 ios）
 * let statPlatform = libs.common.getStatPlatform(PLATFORM, os);
 */
common.getStatPlatform = function(PLATFORM, os) {
	let statPlatform = common.getUniPlatform(PLATFORM);
	if (statPlatform === "app") {
		statPlatform = os;
	}
	return statPlatform;
};

/**
 * 自动根据字符串路径获取对象中的值支持.和[] , 且任意一个值为undefined时,不会报错,会直接返回undefined
 * @param	{Object} dataObj 数据源
 * @param	{String} name 支持a.b 和 a[b]
 * libs.common.getData(dataObj, name);
 */
common.getData = function(dataObj, name, defaultValue) {
	let newDataObj = JSON.parse(JSON.stringify(dataObj));
	let k = "",
		d = ".",
		l = "[",
		r = "]";
	name = name.replace(/\s+/g, k) + d;
	let tstr = k;
	for (let i = 0; i < name.length; i++) {
		let theChar = name.charAt(i);
		if (theChar != d && theChar != l && theChar != r) {
			tstr += theChar;
		} else if (newDataObj) {
			if (tstr != k) newDataObj = newDataObj[tstr];
			tstr = k;
		}
	}
	if (typeof newDataObj === "undefined" && typeof defaultValue !== "undefined") newDataObj = defaultValue;
	return newDataObj;
};

module.exports = common;
